var fs = require('fs');
var express = require('express');
var multer  = require('multer');
var walk = require('walk');
var pathMod = require("path");
const utils = require('./utils.js');
const logs = require('./logs.js');
var request = require('request');

var router = express.Router();
var upload = multer({dest: 'upload_tmp/'});

router.post('/up', upload.any(), function(req, res, next) {
	logs.logvar(req.body);
	logs.logvar(req.files[0]);  // 上传的文件信息

	const des_file = `${utils.userPath(req.body.id)}/${req.files[0].originalname}`;
	//var des_file = `./upload/${path}/` + req.files[0].originalname;
	logs.logvar(des_file);

	fs.readFile( req.files[0].path, function (err, data) {
		if(!fs.existsSync(`${utils.userPath(req.body.id)}/`)){
			fs.mkdirSync(`${utils.userPath(req.body.id)}/`);
		}
		fs.writeFile(des_file, data, function (err) {
			if( err ){
				console.log( err );
				res.send( {result: null, error:err} );
			}else{
				response = {
					result:'ok',
					error:null
				};
				console.log( response );
				res.send( JSON.stringify( response ) );
			}
		});
	});
});

router.get('/down', async (req, res) => {
	try{
		logs.logvar(req.query);
		//await mongodb.login(req.body);
		res.set({
			"Content-Type":"application/octet-stream", //告诉浏览器这是一个二进制文件
			"Content-Disposition":`attachment; filename=${req.query.file}`
		});
		const file = `${utils.userPath(req.query.user)}/${req.query.file}`;
		logs.logvar(file);
		fs.createReadStream(file).pipe(res);
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/down', async (req, res) => {
	try{
		logs.logvar(req.body);
		//await mongodb.login(req.body);
		res.set({
			"Content-Type":"application/octet-stream", //告诉浏览器这是一个二进制文件
			"Content-Disposition":`attachment; filename=${req.body.file}`
		});
		const file = `${utils.userPath(req.body.id)}/${req.body.file}`;
		logs.logvar(file);
		fs.createReadStream(file).pipe(res);
	}catch (e) {
		logs.logvar(e);
		res.send({result: null, error: e.stack});
	}
});

router.post('/list', async function(req, res, next) {
	try{
		const files = await utils.getFileList(req.body.id);
		logs.logvar(files);

		res.send( {result: files, error:null} );
	}catch (e) {
		logs.logvar(e);
		res.send( {result: null, error:e} );
	}
});

module.exports = router;
